/**
 *
 */
package cn.hg.jfsa.manage.controller.module.goods;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.plugin.ehcache.EvictInterceptor;

import cn.hg.base.jfinal.controller.BaseController;
import cn.hg.base.kit.StrExtKit;
import cn.hg.jfsa.core.JfsaThreadLocal;
import cn.hg.jfsa.manage.controller.module.goods.validator.GoodsCategoryValidator;
import cn.hg.jfsa.manage.service.GoodsService;
import cn.hg.jfsa.manage.web.LayuiPage;
import cn.hg.jfsa.model.GoodsCategory;
import cn.hg.jfsa.model.JfsaAdmin;
import cn.hg.jfsa.web.theme.ThemeManager;

/**
 * @author Golly
 */
public class GoodsCategoryController extends BaseController {

	/**
	 * 商品分类服务
	 */
	@Inject
	private GoodsService goodsService;

	/**
	 * 跳转到新增页面
	 */
	public void add () {
		Integer parentId = this.getParaToInt("parentId", 0);
		GoodsCategory parent = new GoodsCategory().setParentId(0).put("parent_name", "").setSortNum(0);

		if (parentId > 0) {
			parent = GoodsCategory.DAO.findById(parentId);
		}

		// 创建新记录
		this.setAttr("goodsCategory", new GoodsCategory().setParentId(parentId).put("parent_name", parent.getName()));
	}

	/**
	 * Ajax删除功能
	 */
	@Before (EvictInterceptor.class)
	@CacheName ("goodsCategory")
	public void ajaxDel () {
		// 通过页面传入的ID查找到记录
		GoodsCategory bean = GoodsCategory.DAO.findById(this.getParaToInt("id"));

		// 记录不存在则报错
		if (null == bean) {
			this.renderAjaxFailed("1", "记录不存在！");
			return;
		}

		boolean successed = Db.tx(new IAtom() {

			@Override
			public boolean run () throws SQLException {
				GoodsCategoryController.this.goodsService.delGoodsCategory(bean, true);
				// 更新父对象的子对象ID列表
				GoodsCategoryController.this.goodsService
					.updateGoodsCategoryChildredIds(GoodsCategory.DAO.findById(bean.getParentId()));
				return true;
			}

		});

		// 返回Ajax成功
		if (successed) {
			this.renderAjaxSuccessed();
		} else {
			this.renderAjaxFailed("1", "操作失败！");
		}

	}

	/**
	 * Ajax方式获取商品分类树
	 */
	@Before (POST.class)
	public void ajaxGetGoodsCategoryTree () {
		this.renderJson(this.goodsService.getGoodsCategoryTree());
	}

	/**
	 * Ajax方式新建或更新记录
	 */
	@Before ({
		GoodsCategoryValidator.class, EvictInterceptor.class
	})
	@CacheName ("goodsCategory")
	public void ajaxSaveOrUpdate () {
		// 获取页面传入的Bean
		GoodsCategory bean = this.getBean(GoodsCategory.class, "goodsCategory");

		if (bean.getParentId() != null && bean.getParentId().equals(bean.getId())) {
			this.renderAjaxFailed("1", "上级分类不能是自己！");
			return;
		}

		JfsaAdmin currAdmin = JfsaThreadLocal.getAdmin();
		GoodsCategory parent = GoodsCategory.DAO.findById(bean.getParentId());
		// 这里引用事务处理是为了方便Ajax模式处理
		boolean successed = Db.tx(new IAtom() {

			@Override
			public boolean run () throws SQLException {

				if (null == bean.getId()) {
					// 初始化数据
					bean.setCreatedTime(new Date()).setCreatorId(currAdmin.getId())
						.setEditorId(currAdmin.getId()).setEditedTime(new Date())
						.setPathIds(parent == null ? ""
							: parent.getPathIds() + (parent.getPathIds().length() > 0 ? "," : "")
								+ parent.getId())
						.setLayerNum(null == parent ? 0 : parent.getLayerNum() + 1)
						.save();
				} else {
					// 更新记录
					bean.setEditorId(currAdmin.getId())
						.setEditedTime(new Date())
						.update();
				}

				// 更新父对象的子对象ID列表
				GoodsCategoryController.this.goodsService.updateGoodsCategoryChildredIds(parent);
				return true;
			}

		});

		// 返回Ajax成功
		if (successed) {
			this.renderAjaxSuccessed();
		} else {
			this.renderAjaxFailed("1", "操作失败！");
		}

	}

	/**
	 * Ajax方式查询
	 */
	// @Before(CacheInterceptor.class)
	// @CacheName("goodsCategory")
	public void ajaxSearch () {
		// 建立查询键值对
		Kv para = Kv.by("sortField", StrExtKit.humpToUnderline(this.getPara("sortField")))
			.set("sortType", this.getPara("sortType"))
			.set("theme", ThemeManager.me().getCurrentTheme().getId());
		// 通过SQL模板引擎构建SQL及参数
		SqlPara sqlPara = Db.getSqlPara("module.findGoodsCategory", para);
		List<GoodsCategory> list = GoodsCategory.DAO.find(sqlPara);
		// 返回Ajax调用的Json结果
		this.renderJson(new LayuiPage(list));
	}

	/**
	 * 跳转到编辑页面
	 */
	public void edit () {
		GoodsCategory bean = GoodsCategory.DAO.findById(this.getParaToInt("id"));
		GoodsCategory parent = GoodsCategory.DAO.findById(bean.getParentId());

		if (parent != null) {
			bean.put("parent_name", parent.getName());
		}

		// 查询目标记录
		this.setAttr("goodsCategory", bean);
	}

	/**
	 * 跳转到列表页面
	 */
	@Before (CacheInterceptor.class)
	@CacheName ("goodsCategory")
	@Override
	public void index () {}

	/**
	 * 跳转到查看页面
	 */
	@Before (CacheInterceptor.class)
	@CacheName ("goodsCategory")
	public void view () {
		GoodsCategory bean = GoodsCategory.DAO.findById(this.getParaToInt("id"));

		if (bean == null) {
			this.render("../record_not_exist.html");
			return;
		}

		GoodsCategory parent = GoodsCategory.DAO.findById(bean.getParentId());

		if (parent != null) {
			bean.put("parent_name", parent.getName());
		}

		this.setAttr("goodsCategory", bean);
	}

}
